var app = getApp();
Page({
    data:{
        siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        good : null,
        address : '',
        buyarr : null,
        taketype : 1,
        name : '',
        tel : '',
        mess : '',
        quantity: {
          quantity: 1,
          min: 1,
          max: 9999
        },
        isback : true,
        cardid : 0,
        isusejifen : 0,
        prompt : [{placeholder:'输入优惠码',response:'yhmcode'}],
        buttons : [{
            type: "default",
            text: "取消",
            fn: "cancelyhm"
        }, {
            type: "primary",
            text: "确定",
            fn: "confirmyhm"
        }],
        actyhm : 0,
        form : false,
        datearr : {date:{}},
        pcard : '',
        shoparr : [],
        isshowshop : false,
        selectshoptid : 0,
        liveid : '',
        isIPX : app.globalData.isIPX,
        showfulldis : false,
        fulldis : [],
        lng : '',
        lat : '',
        totaldis : 0,
        pre_total : 0,
        usedcard : [],
        isshowpaycard : false,
        paynumber : '',
        paycid : '',
    },
    onShow(){
        var cache = wx.getStorageSync('zfssbuy');
        if( (!cache || cache == "") && this.data.isback ){
            wx.navigateBack();
        }
    },
    onLoad:function(options){
        var self = this;

        app.com.getLocation(self,function(loc){
            app.com.auth(function(user){
                var cache = wx.getStorageSync('zfssbuy');
                if( !cache || cache == "" ){
                    //wx.navigateBack();
                }else{
                    var postdata = {
                        op : 'info',
                        gid : cache.gid ? cache.gid : 0,
                        cid : cache.cid ? cache.cid : 0,
                        num : cache.num ? cache.num : 1,
                        groupid : cache.groupid ? cache.groupid : 0,
                        cartlist : cache.arr ? JSON.stringify( cache.arr ) : [],
                        type : cache.type,
                        mapid : cache.mapid,
                        groupmem : cache.groupmem ? cache.groupmem : '',
                        addcart : 1,
                        lat : options.lat > 0 ? options.lat : (loc.latitude ? loc.latitude : 0),
                        lng : options.lng > 0 ? options.lng : (loc.longitude ? loc.longitude : 0),
                        ischangeadd : options.lat > 0 ? 1 : 0,
                    };
                    self.data.lat = postdata.lat;
                    self.data.lng = postdata.lng;

                    app.com.http('confirmv1_v1','POST',postdata,0,false,'','',function(res){
                        if(!res.data.errno  && res.data){
                            self.setData({
                                isusejifen : 0,
                                jifendis : 0,
                                params : res.data.data.params,
                                goodlist : res.data.data.goodlist ? res.data.data.goodlist : [],
                                userinfo : res.data.data.userinfo,
                                name : res.data.data.params.ordername,
                                tel : res.data.data.params.ordertel,
                                pcard : res.data.data.params.orderpcard,
                                num : 1,
                                buytype : cache.type,
                                mapid : cache.mapid,
                                groupmem : cache.groupmem ? cache.groupmem : 0,
                                mapname : cache.mapname ? cache.mapname : '',
                                groupid : cache.groupid ? cache.groupid : 0,
                                liveid : cache.liveid ? cache.liveid : '',
                                cid : cache.cid ? cache.cid : 0,
                                inited : true,
                                allcard : res.data.data.allcard ? res.data.data.allcard : [],
                                taketype : res.data.data.params.taketype,
                                paytype : res.data.data.params.paytype,
                                myredbag : res.data.data.myredbag ? res.data.data.myredbag : false,
                                form : res.data.data.form ? res.data.data.form : false,
                                ctaddress :  res.data.data.userinfo.ctyaddress ? res.data.data.userinfo.ctyaddress : '',
                                ctyarea : res.data.data.myaddress ? res.data.data.myaddress.ctyarea : '',
                            },function(){
                                if(postdata.ischangeadd == 0 && options.setadd != 1){
                                    self.setData({
                                        aname : res.data.data.myaddress ? res.data.data.myaddress.name : '',
                                        atel : res.data.data.myaddress ? res.data.data.myaddress.tel : '',
                                        address : res.data.data.myaddress ? res.data.data.myaddress.address : '',
                                        lat : res.data.data.myaddress ? res.data.data.myaddress.lat : self.data.lat,
                                        lng : res.data.data.myaddress ? res.data.data.myaddress.lng : self.data.lng,
                                    })
                                }
                                self.countData();
                            });
                            
                            //self.countData();
                        }else if( res.data.errno == 2 ){
                            app.com.alert('你还有未支付的订单，请先支付',function(){
                                wx.setStorageSync('zfssbuy','');
                                var tourl = '/zofui_sales/order/orderinfo?id='+res.data.data.orderid;
                                wx.navigateTo({
                                  url: tourl
                                });
                            });
                        }else if( res.data.errno == 3 ){
                            app.com.confirm(res.data.message,function(){
                                wx.setStorageSync('zfssbuy','');
                                var tourl = '/zofui_sales/ucard/buycard';
                                wx.navigateTo({
                                  url: tourl
                                });
                            },function(){
                                wx.navigateBack();
                            },'取消','购买会员');
                        }else{
                            app.com.alert(res.data.message,function(){
                                wx.navigateBack();
                            });
                        }
                    })
                }
            });
        })

        wx.setNavigationBarTitle({
          title:  '确认订单',
        });
        app.onHide();
    },
    changeTakeType( e ){
        var type = e.currentTarget.dataset.type;
        if( type == this.data.taketype ) return false;
        this.setData({
            taketype : type
        });
        this.countData();
    },
    FormIdsubmit : function(e){},
    countData(){
        var self = this;
        
        var pre_total = 0;
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i].list;
            var in_total = 0;
            for (var j = 0; j < item.length; j++) {

                item[j].showPrice_cot = item[j].showPrice;
                item[j].show_userpricejb_cot = item[j].show_userpricejb;
                item[j].priprice = self.data.paytype == 0 || item[j].showPricejb <= 0 ? item[j].showPrice : item[j].showPricejb;
                item[j].priprice_cot = item[j].priprice;
                if( item[j].dateptype*1 == 1 && item[j].yydate && item[j].datepriceres ){
                    for (var k = 0; k < item[j].datepriceres.length; k++) {
                        if(item[j].datepriceres[k].date == item[j].yydate){
                            item[j].priprice = self.data.paytype == 0 || item[j].datepriceres[k].showPricejb <= 0 ? item[j].datepriceres[k].showPrice : item[j].datepriceres[k].showPricejb;
                            item[j].showPrice_cot = item[j].datepriceres[k].showPrice;
                            item[j].show_userpricejb_cot = item[j].datepriceres[k].show_userpricejb;
                        }
                    }
                }
                item[j].prototal = item[j].priprice * item[j].num *100/100;
                in_total += item[j].prototal;
            }
            self.data.goodlist[i].in_total = in_total;
            pre_total += in_total;
        }

        var total = 0;
        var redbagdis = 0;
        var totaldis = 0;
        
        // 0未确定 1平台 2商户
        var isfulldispt = 0;

        for (var i = 0; i < self.data.goodlist.length; i++) {
            var carddis = 0;
            var inproall = 0;
            var intotal = 0;
            var costexpfee = 0;
            var item = self.data.goodlist[i].list;
            

            for (var j = 0; j < item.length; j++) {
                var myredbagdis = 0;
                var redbagid = 0;

                var showPrice_cot = item[j].showPrice_cot;
                var show_userpricejb_cot = item[j].show_userpricejb_cot;
                var priprice = item[j].priprice;
                var priprice_cot = item[j].priprice_cot;
                
                var prototal = item[j].prototal;

                // 包装费
                var costpakfee = 0;
                if( item[j].pakfee*1 > 0 && (self.data.goodlist[i].paktype*1 == 0 || (self.data.goodlist[i].paktype*1 == 1 && self.data.taketype*1 == 2) ) ){
                    costpakfee = item[j].pakfee* (item[j].pre_paktimes*1 == 1 ? item[j].num : 1);
                }

                intotal += costpakfee*1;
                intotal += prototal*1;
                inproall += prototal*1;

                if( item[j].myredbag && prototal > item[j].myredbag.use*1 && prototal > item[j].myredbag.fee*1 ){
                    myredbagdis = item[j].myredbag.fee*1;
                    intotal -= myredbagdis;
                    redbagid = item[j].myredbag.id;

                    totaldis += myredbagdis;
                }

                var namearr = [];
                if(item[j].singletel == 1 && item[j].num > 0){
                    for (var k = 0; k < item[j].num; k++) {

                        var name = k == 0 && this.data.name ? this.data.name : '';
                        var tel = k == 0 && this.data.tel ? this.data.tel : '';
                        var innitem = item[j].oname && item[j].oname[k] ? item[j].oname[k] : {name:name,tel:tel,pcard:''};
                        namearr.push(innitem);
                    }
                }else{
                    namearr = [];
                }

                self.setData({
                    ['goodlist['+i+']list['+j+'].showPrice_cot'] : showPrice_cot,
                    ['goodlist['+i+']list['+j+'].show_userpricejb_cot'] : show_userpricejb_cot,
                    ['goodlist['+i+']list['+j+'].priprice'] : priprice_cot,
                    ['goodlist['+i+']list['+j+'].myredbagdis'] : myredbagdis,
                    ['goodlist['+i+']list['+j+'].redbagid'] : redbagid,
                    ['goodlist['+i+']list['+j+'].costpakfee'] : costpakfee,
                    ['goodlist['+i+']list['+j+'].oname'] : namearr,
                });
            }

            var fulldiss = 0;
            var fullitem = self.data.goodlist[i].fulldisparams;
            if(fullitem){
                for (var j = 0; j < fullitem.length; j++) {
                    let disperfee = fullitem[j].shopid == -1 ? pre_total*1 : self.data.goodlist[i].in_total*1;
                    var fulldissfee = 0;

                    if( fullitem[j].shopid == -1 && isfulldispt <= 1){
                        if(self.data.params.dzbbb*1 == 1 || self.data.params.fulldst == 1) isfulldispt = 1;

                        var fulldissfee = (fullitem[j].diss* (self.data.goodlist[i].in_total*1/pre_total) ).toFixed(2) * 1;
                    }else if( fullitem[j].shopid > 0 && (isfulldispt == 0 || isfulldispt == 2) ){
                        if(self.data.params.dzbbb*1 == 1 || self.data.params.fulldst == 1) isfulldispt = 2;
                        var fulldissfee = fullitem[j].diss*1;
                    }

                    if( fullitem[j].fee*1 <= disperfee &&  fulldissfee > 0){
                        fulldiss = fulldissfee*1 >= intotal*1 ? intotal*1 : fulldissfee*1;
                        intotal -= fulldissfee;
                        intotal = intotal <= 0 ? 0 : intotal;

                        inproall -= fulldissfee;
                        inproall = inproall <= 0 ? 0 : inproall;

                        totaldis += fulldiss;
                        break;
                    }
                }
            }

            if( self.data.goodlist[i].cardid > 0 ){
                var allcard = self.data.goodlist[i].allcard;
                for (var j = 0; j < allcard.length; j++) {
                    if( allcard[j].id == self.data.goodlist[i].cardid){

                        let disperfee = allcard[j].shopid*1 <= 0 ? pre_total*1 : self.data.goodlist[i].in_total*1;

                        if( allcard[j].shopid*1 <= 0 ){
                            var carddissfee = (allcard[j].fee* (self.data.goodlist[i].in_total*1/pre_total) ).toFixed(2) * 1;
                        }else{
                            var carddissfee = allcard[j].fee*100/100;
                        }

                        if( disperfee >= allcard[j].use*1 && carddissfee > 0){
                            carddis = carddissfee*1 >= intotal*1 ? intotal*1 : carddissfee*1;
                            intotal -= carddis;
                            intotal = intotal <= 0 ? 0 : intotal;

                            inproall -= carddis*1;
                            inproall = inproall <= 0 ? 0 : inproall;

                            totaldis += carddis;
                        }
                    }
                }
            }

            if( self.data.goodlist[i].yhmdis > 0 ){
                intotal -= self.data.goodlist[i].yhmdis;
                intotal = intotal <= 0 ? 0 : intotal;

                inproall -= self.data.goodlist[i].yhmdis*1;
                inproall = inproall <= 0 ? 0 : inproall;
            }

            // 快递费
            var costexpfee = 0;
            if( self.data.taketype == 2 && self.data.goodlist[i].expfee*1 > 0 ){
                costexpfee = self.data.goodlist[i].expfee*1;
                if( self.data.goodlist[i].freeexp*1 > 0 && inproall*1 > self.data.goodlist[i].freeexp*1 ){
                    costexpfee = 0;
                }
                intotal += costexpfee;
            }


            intotal = intotal <= 0 ? 0 : intotal;
            let usecardid = carddis > 0 && self.data.goodlist[i].cardid ? self.data.goodlist[i].cardid : 0;
            self.setData({
                ['goodlist['+i+'].fulldiss'] : fulldiss,
                ['goodlist['+i+'].costexpfee'] : costexpfee,
                ['goodlist['+i+'].inproall'] : self.data.goodlist[i].in_total,
                ['goodlist['+i+'].intotal'] : intotal,
                ['goodlist['+i+'].carddis'] : carddis,
                ['goodlist['+i+'].cardid'] : usecardid,
            });
            if(usecardid <= 0){
                self.countusecard();
            }

            total += intotal;
        }

        var jifendis = 0;
        if( self.data.isusejifen == 1 && self.data.userinfo.jifen > 0 && self.data.params.jfpay > 0 ){
            var candis = Math.floor(100 * self.data.userinfo.jifen/self.data.params.jfpay) / 100;
            var usejifen = candis*1 >= (total*1 - costexpfee) ? (total*1 - costexpfee) : candis*1;
            usejifen = item[0].jfdkmax > 0 && item[0].jfdkmax*1 < usejifen ? item[0].jfdkmax*1 : usejifen;

            jifendis = usejifen >= 0.01 ? usejifen.toFixed(2)*1 : 0;
        }
        if( jifendis > 0 ){
            total = total - jifendis*1;
            totaldis += jifendis;
        }

        self.setData({
            pre_total : pre_total,
            total : total.toFixed(2) *1,
            myredbagdis : myredbagdis,
            jifendis : jifendis,
            cardid : carddis <= 0 ? 0 : self.data.cardid,
            totaldis : totaldis.toFixed(2) *1,
        });
    },
    selectAddress : function( e ){
        var self = this;
        wx.chooseAddress({
            success: function (res) {
                self.setData({
                    address : {
                        name:res.userName,
                        province : res.provinceName,
                        city:res.cityName,
                        county:res.countyName,
                        detail:res.detailInfo,
                        tel:res.telNumber
                    },
                    province : res.provinceName,
                    city : res.cityName,
                    country : res.countyName,
                });
            }
        });
    },
    handleZanQuantityChange(e) {
        var componentId = e.componentId;
        var quantity = e.quantity;

        this.setData({
          [`${componentId}.quantity`]: quantity,
          num : quantity,
        });
        this.countData();
    },
    handleZanFieldChange(e) {
        const { componentId, detail } = e;
        this.setData({
            tel : detail.value,
        });
    },
    miusVal(e,inputnum){
        var self = this;
        var i = e.currentTarget.dataset.i;
        var j = e.currentTarget.dataset.ii;
        var type = e.currentTarget.dataset.type;
        var num = inputnum;

        var item = self.data.goodlist[i].list;
        if( type == 1 ){
            num = item[j].num*1 - 1;
            if( item[j].num <= 1 ){
                num = 1;
            }
        }else if(type == 2){
            num = item[j].num*1 + 1;
            if( item[j].num*1 >= item[j].stock*1 ){
                num = item[j].stock;
            }
        }else if(type == 3){
            if( num*1 > item[j].stock*1 ) num = item[j].stock;
        }

        self.setData({
            ['goodlist['+i+']list['+j+'].num'] : num,
        });
        self.countData();
    },
    bindVal(e){
        var self = this;
        var i = e.currentTarget.dataset.i;
        var ii = e.currentTarget.dataset.ii;
        var num = e.detail.value;
        var ea = {
        	currentTarget : {
        		dataset : {
        			i : i,
                    ii : ii,
        			type : 3,
        		}
        	}
        }
        self.miusVal(ea,num);
    },
    onamechange(e){
        var i = e.currentTarget.dataset.i;
        var ii = e.currentTarget.dataset.ii;
        var iii = e.currentTarget.dataset.iii;
        var type = e.currentTarget.dataset.type;
        this.setData({
            ['goodlist['+i+'].list['+ii+'].oname['+iii+'].'+type] : e.detail.value,
        });
        if(i == 0 && ii == 0 && iii == 0){
            if(type == 'name' && !this.data.name){
                this.setData({
                    name : e.detail.value
                })
            }
            if(type == 'tel' && !this.data.tel){
                this.setData({
                    tel : e.detail.value
                })
            }
            if(type == 'pcard'){
                this.setData({
                    pcard : e.detail.value
                })
            }
        }
    },
    setdate(e){
        var self = this;
        var id = e.currentTarget.dataset.id;
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i].list;
            for (var j = 0; j < item.length; j++) {
                if( item[j].id == id ){
                    
                    self.setData({
                        datearr : {
                            actid : id,
                            carttid : self.data.buytype == 'cart' ? id : '',
                            mapid : self.data.buytype == 'cart' ? '' : self.data.mapid,
                            actgid : item[j].gid,
                            date : item[j].dateday,
                            time : item[j].datetimes,
                            isprice : item[j].dateptype || 0,
                            priprice : item[j].priprice,
                            pricearr : item[j].dateptype == 1 && item[j].datepriceres ? item[j].datepriceres : [],
                            paytype : self.data.paytype,
                        }
                    },function(){
                        self.selectComponent('#showdate').showthis();
                    });
                    break;
                }
            }
        }
        
        self.showdatefn();
    },
    setshop(e){
        var self = this;
        var i = e.currentTarget.dataset.i;
        var j = e.currentTarget.dataset.ii;

        var item = self.data.goodlist[i].list;
        self.setData({
            shoparr : item[j].shoplist,
            selectshoptid : {i:i,j:j},
        });
        this.showshopfn();
    },
    showshopfn(e){
        this.setData({
            isshowshop : !this.data.isshowshop,
        });
    },
    comshopfn(e){
        var self = this;
        var id = e.currentTarget.dataset.id;
        var name = e.currentTarget.dataset.name;

        var i = self.data.selectshoptid.i;
        var j = self.data.selectshoptid.j;
        self.setData({
            ['goodlist['+i+']list['+j+'].toshopid'] : id,
            ['goodlist['+i+']list['+j+'].toshopname'] : name,
        });
        this.showshopfn();
    },
    showdatefn(){
        this.setData({
            showdate : !this.data.showdate,
            actdate : '',
            acttime : '',
        });
    },
    confirmdate(e){
        var self = this;
        var id = self.data.datearr.actid;
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i].list;
            for (var j = 0; j < item.length; j++) {
                if( item[j].id == id ){
                    self.setData({
                        ['goodlist['+i+']list['+j+'].yydate'] : e.detail.date,
                        ['goodlist['+i+']list['+j+'].yytime'] : e.detail.time ? e.detail.time : '',
                    });
                    break;
                }
            }
        }
        self.showdatefn();
        self.countData();
    },
    messchange( e ){
        this.setData({
            mess : e.detail.value,
        });
    },
    tel(e){
        this.setData({
            tel : e.detail.value,
        });
    },
    name(e){
        this.setData({
            name : e.detail.value,
        });
    },  
    mess(e){
        this.setData({
            mess : e.detail.value,
        });
    },
    card(e){
        this.setData({
            pcard : e.detail.value,
        });
    },
    confirm(e){
    	var self = this;
    	var subform = [];
        
        if( !self.data.name && self.data.taketype == 1 && self.data.params.coname == 0 ) {
            app.com.toast('请填写姓名');
            return false;
        }
        if( !app.com.verify('mobile', self.data.tel ) && self.data.taketype == 1 && self.data.params.cotel == 0 ) {
            app.com.toast('请填写正确的电话号码');
            return false;
        }
        if( self.data.form ){
            for (var i = 0; i < self.data.form.length; i++) {   
                if( !self.data.form[i].value ){
                    app.com.toast('请完善'+self.data.form[i].name);
                    return false;
                }
                subform.push({
                    name : self.data.form[i].name,
                    value : self.data.form[i].value,
                });
            }
        }

        var goodlist = [];
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i];
            var into = { cardid : item.cardid ,yhmcode:item.yhmcode, list : [] };
            for (var j = 0; j < item.list.length; j++) {
                into.list.push({
                    id : item.list[j].id,
                    gid : item.list[j].gid,
                    num : item.list[j].num,
                    redid : item.list[j].redbagid,
                    yydate : item.list[j].yydate ? item.list[j].yydate : '',
                    yytime : item.list[j].yytime ? item.list[j].yytime : '',
                    toshopid : item.list[j].toshopid ? item.list[j].toshopid : '',
                    oname : item.list[j].oname ? item.list[j].oname : '',
                });
            }
            goodlist.push(into);
        }

        var pidarr = wx.getStorageSync('tclist');

        var postdata = {
            op:'pay',
            taketype : self.data.taketype,
            paytype : self.data.paytype,
            name:self.data.name,
            tel:self.data.tel,
            pcard : self.data.pcard,
            mess : self.data.mess,
            num : self.data.num,
            buytype : self.data.buytype,
            groupid : self.data.groupid,
            cid : self.data.cid,
            aname : self.data.aname,
            atel : self.data.atel,
            province : self.data.province ? self.data.province : '',
            city : self.data.city ? self.data.city : '',
            country : self.data.country ? self.data.country : '',
            address : self.data.address,
            ctyarea : self.data.ctyarea ? self.data.ctyarea : '',
            liveid : self.data.liveid ? self.data.liveid : '',
            cardid : self.data.cardid,
            isusejifen : self.data.isusejifen ? self.data.isusejifen : 0,
            jifendis : self.data.jifendis > 0 ? self.data.jifendis : 0,
            ctaddress : self.data.ctaddress ? self.data.ctaddress : '',
            groupmem : self.data.groupmem ? self.data.groupmem : 0,
            mapid : self.data.mapid ? self.data.mapid : '',
            addcart : 1,// 新版的
            goodlist : goodlist ? JSON.stringify( goodlist ) : [],
            subform : subform ? JSON.stringify( subform ) : 0,
            lat : self.data.lat,
            lng : self.data.lng,
            pidarr : pidarr ? JSON.stringify( pidarr ) : [],
            paynumber : self.data.paynumber ? self.data.paynumber : '',
            paycid : self.data.paycid ? self.data.paycid : '',
        };
        
        if( self.data.payed ) return false;
        self.data.payed = true;

        app.com.http('confirmv1_v1','POST',postdata,0,true,'','',function(res){
            self.data.payed = false;
            if (!res.data.errno && res.data) {
                wx.setStorageSync('zfssbuy','');
                if( res.data.data.payed == 1 ){
                    self.paysuc(res.data.data,self.data.buytype);
                    if( res.data.data.channel ){
                        app.com.sendGo(res.data.data.gomess,res.data.data.channel);
                    }
                }else{
                    self.setData({ // 防止返回商品
                        isback : false,
                    })
                    wx.requestPayment({
                        'appId' : res.data.data.appId,
                        'timeStamp': res.data.data.timeStamp,
                        'nonceStr': res.data.data.nonceStr,
                        'package': res.data.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.data.paySign,
                        'success': function (payres) {
                            if( payres.errMsg == 'requestPayment:ok' ){
                                self.paysuc(res.data.data,self.data.buytype);
                                if( res.data.data.channel ){
                                    app.com.sendGo(res.data.data.gomess,res.data.data.channel);
                                }
                            }
                        },
                        'fail': function (payres) {
                            var tip = self.data.params.fontsty == 33 ? '请尽快提交' : '请尽快支付';

                            app.com.toast(tip,'fail',function(){
                                var tourl = '/zofui_sales/order/orderinfo?id='+res.data.data.orderid;
                                if( self.data.buytype == 'cart' ) {
                                    tourl = '/zofui_sales/order/orderlist?dealid'+res.data.data.orderid;
                                    if(self.data.params.shopnav*1 == 1){
                                        tourl += '?shopid='+self.data.goodlist[0].shopid;
                                    }
                                }
                                wx.navigateTo({
                                    url: tourl,
                                    complete : function(){
                                        self.setData({
                                            isback : true,
                                        })
                                    }
                                });

                            });
                        }
                    });
                }
            }else{
            	app.com.alert(res.data.message);
            }
        });
    	
    },
    navigateto : function( e ){
        app.com.navigateto( e,this.data.tid );
    },
    paysuc(payres,peytype){
        var self = this;
        var tip = self.data.params.fontsty == 33 ? '已经提交' : '支付完成';
        app.com.toast(tip,'success',function(){

            if( peytype == 1 || peytype == 2 ){ // 拼团
                self.checkGroup(payres.orderid);
            }else{
                var tourl = '/zofui_sales/order/orderinfo?id='+payres.orderid;
                if( self.data.buytype == 'cart' ) {
                    tourl = '/zofui_sales/order/orderlist?dealid='+payres.orderid;
                    if(self.data.params.shopnav*1 == 1){
                        tourl += '?shopid='+self.data.goodlist[0].shopid;
                    }
                }
                if(payres.suctourl){
                    tourl = payres.suctourl;
                }
                wx.navigateTo({
                    url: tourl,
                    complete : function(){
                        self.setData({
                            isback : true,
                        })
                    }
                });
            }

        });
    },
    checkGroup(orderid){
        var self = this;
        setTimeout(function(){
            app.com.http('confirmv1_v1','POST',{orderid:orderid,op:'checkgroup'},0,false,'','',function(res){
                if (!res.data.errno  && res.data) {
                    var tourl = '/zofui_sales/group/group?id='+res.data.data.groupid;
                    wx.navigateTo({
                        url: tourl,
                        complete : function(){
                            self.setData({
                                isback : true,
                            })
                        }
                    });
                }else{
                    self.checkGroup(orderid);
                }
            });
        },500);
    },
    zitiChange(e){
        var self = this;
        self.setData({
            taketype : e.detail.value,
        });
        this.countData();
    },
    payChange(e){
        var self = this;

        if( self.data.userinfo.level != 1 && self.data.params.muse == 1 ){
            app.com.confirm('只有会员才能使用'+self.data.params.umname,function(){
                var tourl = '/zofui_sales/ucard/buycard';
                wx.navigateTo({
                  url: tourl
                });
            },false,'取消','购买会员');

            self.setData({
                paytype : 0,
            });
            return false;
        }

        self.setData({
            paytype : e.detail.value,
        });
        self.countData();
    },
    jifenChange(e){
        var self = this;
        self.setData({
            isusejifen : e.detail.value,
        });
        self.countData();
    },
    openSetting(){
        var self = this;
        wx.navigateTo({
            url : '/zofui_sales/user/address?from=choose'
        })
    },
    setaddress(e){

        var address = e.province+e.city+e.country+e.street;
        if(this.data.params.wxptp*1 == 1){
            address = e.street + '，'+e.city+' '+ (e.pshort ? e.pshort : e.province)+' '+ (e.code ? e.code : '');
        }

        this.setData({
            aname : e.name ? e.name : '',
            atel : e.tel ? e.tel : '',
            address : address,
            ctyarea : e.province+','+e.city+','+e.country,
            province : e.province ? e.province : '',
            city : e.city ? e.city : '',
            country : e.country ? e.country : '',
            lat : e.lat ? e.lat : '',
            lng : e.lng ? e.lng : '',
        });
        var options = {
            lat : e.lat ? e.lat : '',
            lng : e.lng ? e.lng : '',
        };
        options.setadd = 1;
        this.onLoad(options);
    },
    hideCard(e){
        var self = this;
        if(e && e.currentTarget.dataset.type*1 == 1){
            var t = {
                currentTarget : {
                    dataset : {
                        i : -1
                    }
                }
            }
            this.usecard(t);
        }else{
            self.setData({
                hideCard : false,
            });
        }
    },
    showCard(e){
        var self = this;
        var index = e.currentTarget.dataset.i;

        for (var i = 0; i < self.data.goodlist[index].allcard.length; i++) {
            self.data.goodlist[index].allcard[i].isused = 0;
            for (var j = 0; j < self.data.usedcard.length; j++) {
                if( self.data.goodlist[index].allcard[i].id == self.data.usedcard[j] ){
                    self.data.goodlist[index].allcard[i].isused = 1;
                }
            }
        }
        self.setData({
            allcard : self.data.goodlist[index].allcard,
            inproall: self.data.goodlist[index].inproall,
            actsid : self.data.goodlist[index].shopid,
            hideCard : true,
        });
    },
    countusecard(){
        var self = this;
        self.data.usedcard = [];
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i];
            if(item.cardid*1 > 0 ){
                self.data.usedcard.push(item.cardid);
            }
        }
    },
    usecard(e){
        var self = this;
        var index = e.currentTarget.dataset.i*1;
        
        self.data.usedcard = [];
        if(index < 0){
            var card = {
                id : '',
                shopid : '',
            }
        }else{
            var card = self.data.allcard[index];
        }
        
        for (var i = 0; i < self.data.goodlist.length; i++) {
            var item = self.data.goodlist[i];
            if(card && card.shopid*1 > 0){
                
                if( item.shopid*1 == self.data.actsid*1 ){
                    self.setData({
                        ['goodlist['+i+'].cardid'] : card.id,
                        ['goodlist['+i+'].useptcard'] : 0,
                    });
                }else if(self.data.params.dzbbb*1 == 1 && item.useptcard == 1){
                    self.setData({
                        ['goodlist['+i+'].cardid'] : 0,
                    });
                }
                
            }else{
                self.setData({
                    ['goodlist['+i+'].cardid'] : card.id,
                    ['goodlist['+i+'].useptcard'] : 1,
                });
            }
            if(card.id > 0){
                self.data.usedcard.push(card.id);
            }
        }
        
        self.countData();
        self.hideCard();
        let tips = card.id ? '已使用' : '已清空';
        app.com.toast(tips);
    },
    bindRegionChange : function(e){
        var self = this;
        self.setData({
            ctaddress : e.detail.value[0] +','+e.detail.value[1] +','+e.detail.value[2]
        })
    },
    setyhm(e){
        var self = this;
        self.setData({
            actyhmsid : e.currentTarget.dataset.sid,
            showsetymh : true,
        })
    },
    cancelyhm(){
        this.setData({
            showsetymh : false,
        })
    },
    confirmyhm(){
        var self = this;
        if( self.data.actyhm ){

            var postdata = {
                code:self.data.actyhm,
                op:'checkyhm',
            };

            for (var i = 0; i < self.data.goodlist.length; i++) {
                var item = self.data.goodlist[i];   
                if( item.shopid == self.data.actyhmsid ){
                    postdata.goodlist = JSON.stringify( self.data.goodlist[i] );
                }
            }

            app.com.http('confirmv1_v1','POST',postdata,0,true,'','',function(res){
                if (!res.data.errno  && res.data) {
                    
                    for (var i = 0; i < self.data.goodlist.length; i++) {
                        var item = self.data.goodlist[i];   
                        if( item.shopid == self.data.actyhmsid ){
                            self.setData({
                                ['goodlist['+i+'].yhmcode'] : self.data.actyhm,
                                ['goodlist['+i+'].yhmdis'] : res.data.data.yhmdis,
                                actyhm : 0,
                                showsetymh : false,
                            });
                        }
                    }
                    
                    self.countData();
                    self.hideCard();

                }else{
                    app.com.toast(res.data.message);
                }
            });
        }else{
            for (var i = 0; i < self.data.goodlist.length; i++) {
                var item = self.data.goodlist[i];   
                if( item.shopid == self.data.actyhmsid ){
                    self.setData({
                        ['goodlist['+i+'].yhmcode'] : '',
                        ['goodlist['+i+'].yhmdis'] : 0,
                        actyhm : 0,
                        showsetymh : false,
                    });
                }
            }
            self.countData();
            self.hideCard();
        }
    },
    yhmcode(e){
        this.setData({
            actyhm : e.detail.value,
        })
    },
    formfn(e){
        var self = this;
        var index = e.currentTarget.dataset.index;
        var value = e.detail.value;
        for (var i = 0; i < self.data.form.length; i++) {
            if(i == index){

                if( self.data.form[i].type == 'single' ){
                    value = self.data.form[i].sdata[value]
                }

                self.setData({
                    ['form['+i+'].value'] : value,
                })
            }
        }
    },
    showmulti(e){
        var self = this;
        var index = e.currentTarget.dataset.index;
        for (var i = 0; i < self.data.form.length; i++) {
            if(i == index){
                self.setData({
                    actmultiindex : index,
                    isshowmulti : true,
                    multidata : self.data.form[i].sdata,
                })
            }
        }
    },
    hideshowmulti(){
        this.setData({
            isshowmulti : false
        })
    },
    onChangemulti(e){
        this.setData({
            multiresult : e.detail
        })
    },
    comfirmmulti(){
        var e = {
            currentTarget : {
                dataset : {
                    index : this.data.actmultiindex
                }
            },
            detail : {
                value : this.data.multiresult
            }
        };
        this.formfn(e);
        this.setData({
            multiresult : [],
            isshowmulti : false,
        })
    },
    setfulldis(e){
        var item = this.data.goodlist[e.currentTarget.dataset.i];
        this.setData({
            showfulldis : true,
            fulldis : item.fulldisparams
        })
    },
    hidefulldis(){
        this.setData({
            showfulldis : false,
        })
    },
    selectarea(){
        this.selectComponent('#ausarea').show();
    },
    showpaycard(){
        this.selectComponent('#paycard').show();
    },
    setpaycard(e){
        var self = this;
        self.setData({
            paynumber : e.detail.paynumber,
            paycid : e.detail.paycid,
        })
    }

})